package com.qsl.service.impl;

import com.qsl.entity.User;
import com.qsl.repository.UserRepository;
import com.qsl.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;

/**
 * @description: xxx描述
 * @author: 博客园@青石路
 * @date: 2024/1/17 20:16
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User save(User user) {
        // 1.保存
        User savedUser = userRepository.save(user);
        // 2.其他db操作

        // 3.发送消息
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {

            @Override
            public void afterCommit() {
                log.info("事务提交之后执行该方法");
            }

            @Override
            public void afterCompletion(int status) {
                log.info("事务完成之后执行该方法");
            }
        });

        return savedUser;
    }
}
